package com.h5lib.nchuoffice.app.dao;

import java.sql.SQLException;
import java.util.List;

import com.h5lib.jdbc.ormlite.SqliteJdbcConnectionSource;
import com.h5lib.server.annotation.Init;
import com.h5lib.server.annotation.Inject;
import com.h5lib.server.annotation.Repository;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.table.TableUtils;

@Repository
public class CacheDao {
	
	@Inject
	private SqliteJdbcConnectionSource connectionSource;
	/**
	 * 
	 */
	private Dao<Cache, String> cacheDao ;
	
	/**
	 * 初始化方法
	 * @param init
	 */
	@Init
	public void init() {
		try {
			cacheDao = DaoManager.createDao(connectionSource,Cache.class);
			TableUtils.createTableIfNotExists(connectionSource, Cache.class);
		} catch (SQLException e) {
			throw new RuntimeException("Problems initializing database objects", e);
		}
	}
	
	/**
	 * 保存实体
	 * @param app
	 * @return
	 * @throws SQLException
	 */
	public Integer saveOrUpdate(Cache cache) throws SQLException {
		Cache cacheDb = cacheDao.queryForId(cache.getKey());
		if(cacheDb == null){
			return cacheDao.create(cache);
		}
		else{
			return cacheDao.update(cache);
		}
	}
	
	/**
	 * 获取全部缓存
	 * @return
	 * @throws SQLException
	 */
	public List<Cache> getCaches() throws SQLException{
		return cacheDao.queryForAll();
	}
	
}
